<template>
  <div>
    <table class="tb">
      <tr>
        <th>
          <label for="all">全选</label>
          <input type="checkbox" @click="xo" id="all" v-model="checkAll" />
        </th>
        <th>产品图片</th>
        <th>编号</th>
        <th>品牌名称</th>
        <th>价格</th>
        <th>数量</th>
        <th>操作</th>
      </tr>
      <tr v-for="(item, index) in goodsList" :key="item.id">
        <td>
          <input type="checkbox" v-model="checkArr" :value="item" />
        </td>
        <td>
          <img :src="item.imgSrc" width="50" height="50" alt="" />
        </td>
        <td>
          {{ item.code }}
        </td>
        <td>
          {{ item.productName }}
        </td>
        <td>
          {{ item.price }}
        </td>
        <td>
          <button @click="dect(item)">-</button>
          &nbsp;
          <b>{{ item.count }}</b>
          &nbsp;
          <button @click="inct(item)">+</button>
        </td>
        <td>
          <button @click="del(index)">删除</button>
        </td>
      </tr>
    </table>
    <div class="total add">
      <h1 style="text-align: right">
        结算：<b style="color: red">{{ total }}</b>
      </h1>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: "all",
      checkArr: [],
      checkAll: false,
    };
  },
  computed: {
    total() {
      if (this.checkArr.length == 0) {
        return "0";
      } else {
        return (this.checkArr.reduce((total, item) => {
            return (total += item.price * item.count);
          }, 0)).toFixed(2);
      }
    },
  },
  watch: {
    checkArr(newch) {
      if (this.goodsList.length === newch.length) {
        this.checkAll = true;
      } else {
        this.checkAll = false;
      }
    },
  },
  methods: {
    xo(e) {
      let checked = e.target.checked;
      if (checked) {
        this.checkArr = this.goodsList;
      } else {
        this, (this.checkArr = []);
      }
    },
    del(index) {
      this.$emit("del", index);
    },
    inct(item) {
      item.count++;
    },
    dect(item) {
      item.count--;
    },
  },
  props: {
    goodsList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
};
</script>

<style scoped>
.tb {
  border-collapse: collapse;
  width: 100%;
}

.tb th {
  background-color: #0094ff;
  color: white;
}

.tb td,
.tb th {
  padding: 5px;
  border: 1px solid black;
  text-align: center;
}
</style>